<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function __construct()
    {
        //
    }

    public function toLogin()
    {
    	return view('admin.login');
    }

    //登录
    public function login(Request $request)
    {
        $username = $request->user_name;
        $password = $request->password;
        $adminUser = AdminUser::where('user_name', $username)->first();
        if (!$adminUser) {
            $data = [
                'status' => 2,
                'msg'    => '用户不存在'
            ];
            return json_encode($data);
        }
        // if (Hash::check($password, $adminUser->password))
        if (password_verify($password, $adminUser->password)) {
            $request->session()->put('admin', $adminUser);
            $data = [
                'status' => 0,
                'msg'    => '登录成功',
                'url'    => route('admin.index')
            ];
        } else {
            $data = [
                'status' => 3,
                'msg'    => '密码错误'
            ];
        }
        return json_encode($data);
    }

    //登出
    public function logout(Request $request)
    {
        $request->session()->forget('admin');
        return redirect(route('admin.login'));
    }

    //修改密码
    public function toSetPwd()
    {
        return view('admin.setPwd');
    }

    //保存密码
    public function setPwd(Request $request)
    {
        if ($request->isXmlHttpRequest()) {
            $this->middleware('admin.auth');
            $this->validate($request, [
                'newpassword' => 'bail|required|min:6',
                'newpassword1' => 'same:newpassword'
            ]);

            if ($request->newpassword != $request->newpassword1) {
                $data = ['status' => 2, 'msg' => '两次密码输入不一致'];
                return json_encode($data);
            }

            $adminUser = session('admin');
            $admin = AdminUser::where('user_name', $adminUser->user_name)->update(['password' => password_hash($request->newpassword, PASSWORD_DEFAULT)]);

            if (!$admin) {
                $data = ['status' => 3, 'msg' => '修改密码失败'];
            } else {
                $request->session()->forget('admin');
                $data = ['status' => 0, 'msg' => '修改密码成功', 'url' => route('admin.index')];
            }
            return json_encode($data);
        }

    }
}
